import json

from django import http
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.paginator import Paginator, EmptyPage
from django.shortcuts import render

# Create your views here.
from django.utils.decorators import method_decorator
from django.views import View
from django.views.decorators.csrf import csrf_exempt

from apps.case.models import Case


class CaseView(View):
    def get(self, request):
        sort = request.GET.get('sort', 'newest')
        if sort == "heated":
            # 按照评论量排序
            sort_field = '-click_nums'
        else:
            # 'price'和'sales'以外的所有排序方式都归为'default'
            sort = 'newest'
            sort_field = '-create_time'

        news = Case.objects.all().order_by(sort_field)

        # 创建分页器：每页N条记录
        paginator = Paginator(news, 10)
        # 获取每页商品数据
        try:
            page_nums = request.GET.get("page")
            # print(page_nums)
            page_num = int(page_nums)
        except:
            page_num = 1
        try:
            page_skus = paginator.page(page_num)
            # print(page_skus)
        except EmptyPage:
            # 如果page_num不正确，默认给用户404
            return http.HttpResponseNotFound('empty page')
        # 获取列表页总页数
        total_page = paginator.num_pages
        # print(news)
        user = request.user
        if sort == "newest":
            if str(user) == "AnonymousUser":
                context = {

                    'num': 1,
                    'sort': sort,  # 排序字段
                    'page_skus': page_skus,  # 分页后数据
                    'total_page': total_page,  # 总页数
                    'page_num': page_num,  # 当前页码
                }
            else:
                context = {
                    'num': 1,
                    'user': user,
                    'sort': sort,  # 排序字段
                    'page_skus': page_skus,  # 分页后数据
                    'total_page': total_page,  # 总页数
                    'page_num': page_num,  # 当前页码
                }

            return render(request, 'case/case.html', context=context)
        elif sort == "heated":
            if str(user) == "AnonymousUser":
                context = {

                    'num': 'tl',
                    'sort': sort,  # 排序字段
                    'page_skus': page_skus,  # 分页后数据
                    'total_page': total_page,  # 总页数
                    'page_num': page_num,  # 当前页码
                }
            else:
                context = {
                    'num': "tl",
                    'user': user,
                    'sort': sort,  # 排序字段
                    'page_skus': page_skus,  # 分页后数据
                    'total_page': total_page,  # 总页数
                    'page_num': page_num,  # 当前页码
                }

            return render(request, 'case/case.html', context=context)


@method_decorator(csrf_exempt, name="dispatch")
class PushView(LoginRequiredMixin, View):
    def post(self, request):
        # title: 4444
        # link: http: // 127.0
        # .0
        # .1: 8000 / case / case
        # desc: 12315615
        # cover: http: // q2fyx80nw.bkt.clouddn.com / FrmS8UjBRunSOEDhSz9WngGOqx - y
        # file:
        # agree: on
        user = request.user
        title = request.POST.get("title")
        case_url = request.POST.get("link")
        content = request.POST.get("desc")
        agree = request.POST.get("agree")
        case = request.POST.get("cover")
        print(title)
        print(case_url)
        print(content)
        print(agree)
        print(case)

        if not all([content, title, case_url, case, agree]):
            ret = {"status": 101, "msg": "缺少参数"}
            return http.HttpResponse(json.dumps(ret), content_type="application/json")
        if agree != "on":
            ret = {"status": 102, "msg": "没有同意"}
            return http.HttpResponse(json.dumps(ret), content_type="application/json")
        try:
            case = Case.objects.create(content=content, case=case, title=title, case_url=case_url, user=user)
        except Case.DoesNotExist:
            ret = {"status": 103, "msg": "发布失败"}
            return http.HttpResponse(json.dumps(ret), content_type="application/json")
        ret = {"status": 0, "msg": "发布成功"}
        return http.HttpResponse(json.dumps(ret), content_type="application/json")
